#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include "Log.hpp"
#include <fstream>
#include "InetAddr.hpp"

using namespace LogModule;

const std::string defaultdict = "./dictionary.txt";
const std::string sep = ": ";

class Dict
{
public:
    Dict(const std::string &path = defaultdict)
        : _dict_path(path)
    {
    }

    // 将字典下载下来
    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "打开字典：" << _dict_path << "错误";
            return false;
        }

        // 从字典里面拿到一行
        std::string line;
        while (std::getline(in, line))
        {
            // apple: 苹果，用分割符将这俩分开
            auto pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "解析：" << line << "失败";
                continue; // 就算失败了，也得继续解析，不能不动了
            }
            // 提取英文和中文
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            // 判断是否为空
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "没有有效内容" << line;
                continue;
            }

            _dict.insert(std::make_pair(english, chinese));
            LOG(LogLevel::DEBUG) << "加载.." << line;
        }
        in.close();
        return true;
    }

    // 翻译功能
    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入到了翻译模块,[" << client.Ip() << ":" << client.Port() << "]#" << word << "->" << "->None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入到了翻译模块,[" << client.Ip() << ":" << client.Port() << "]#" << word << "->" << iter->second;
        return iter->second;
    }

    ~Dict()
    {
    }

private:
    std::string _dict_path;                             // 字典的路径和文件名
    std::unordered_map<std::string, std::string> _dict; // 字典
};